package com.cy.ragbase.controller;

import com.cy.ragbase.dto.*;
import com.cy.ragbase.entity.CodeBlock;
import com.cy.ragbase.service.CodeBlockService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;


@RequiredArgsConstructor
@Slf4j
@RestController
public class CodeGenerateController {

    private final CodeBlockService codeBlockService;


    /**
     * 通过JSON文件批量导入代码块
     */
    @PostMapping("/codeblocks/import")
    public ResponseEntity<CodeBlockImportResponse> importCodeBlocksFromFile(
            @RequestParam("file") MultipartFile file) {
        try {
            // 验证文件类型
            if (!isValidJsonFile(file)) {
                CodeBlockImportResponse errorResponse = new CodeBlockImportResponse();
                errorResponse.setStatus("FAILED");
                errorResponse.setMessage("请上传有效的JSON文件");
                errorResponse.setSuccessCount(0);
                errorResponse.setFailureCount(0);
                errorResponse.setTotalCount(0);
                return ResponseEntity.badRequest().body(errorResponse);
            }

            CodeBlockImportResponse response = codeBlockService.importCodeBlocksFromFile(file);
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Code blocks import from file failed", e);

            CodeBlockImportResponse errorResponse = new CodeBlockImportResponse();
            errorResponse.setStatus("FAILED");
            errorResponse.setMessage("代码块导入失败: " + e.getMessage());
            errorResponse.setSuccessCount(0);
            errorResponse.setFailureCount(0);
            errorResponse.setTotalCount(0);

            return ResponseEntity.badRequest().body(errorResponse);
        }
    }

    /**
     * 搜索代码块
     */
    @PostMapping("/codeblocks/search")
    public ResponseEntity<CodeSearchResponse> searchCodeBlocks(@RequestBody CodeSearchRequest request) {
        try {
            CodeSearchResponse response = codeBlockService.searchCodeBlocks(request);
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Code blocks search failed for query: {}", request.getQuery(), e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 代码辅助RAG - 生成代码开发提示词
     */
    @PostMapping("/code/rag")
    public ResponseEntity<CodeRagResponse> generateCodeRagPrompt(@RequestBody CodeRagRequest request) {
        try {
            CodeRagResponse response = codeBlockService.generateCodeRagPrompt(request);
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Code RAG prompt generation failed for requirement: {}", request.getRequirement(), e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 验证是否为有效的JSON文件
     */
    private boolean isValidJsonFile(MultipartFile file) {
        if (file.isEmpty()) {
            return false;
        }

        String fileName = file.getOriginalFilename();
        if (fileName == null) {
            return false;
        }

        return fileName.toLowerCase().endsWith(".json");
    }

    /**
     * 获取代码块统计信息
     */
    @GetMapping("/codeblocks/stats")
    public ResponseEntity<Map<String, Object>> getCodeBlockStats() {
        try {
            Map<String, Object> stats = codeBlockService.getCodeBlockStats();
            return ResponseEntity.ok(stats);
        } catch (Exception e) {
            log.error("Failed to get code block stats", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 获取所有代码块列表（分页）
     */
    @GetMapping("/codeblocks")
    public ResponseEntity<List<CodeBlock>> getAllCodeBlocks() {
        try {
            List<CodeBlock> codeBlocks = codeBlockService.getAllCodeBlocks();
            return ResponseEntity.ok(codeBlocks);
        } catch (Exception e) {
            log.error("Failed to get all code blocks", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 根据ID获取代码块
     */
    @GetMapping("/codeblocks/{id}")
    public ResponseEntity<CodeBlock> getCodeBlock(@PathVariable String id) {
        try {
            CodeBlock codeBlock = codeBlockService.getCodeBlockById(id);
            if (codeBlock == null) {
                return ResponseEntity.notFound().build();
            }
            return ResponseEntity.ok(codeBlock);
        } catch (Exception e) {
            log.error("Failed to get code block: {}", id, e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 删除代码块
     */
    @DeleteMapping("/codeblocks/{id}")
    public ResponseEntity<Void> deleteCodeBlock(@PathVariable String id) {
        try {
            boolean deleted = codeBlockService.deleteCodeBlock(id);
            if (deleted) {
                return ResponseEntity.ok().build();
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            log.error("Failed to delete code block: {}", id, e);
            return ResponseEntity.internalServerError().build();
        }
    }

}
